import { message, Tag } from 'ant-design-vue'
import type { SpColumnsType } from '@/components/SpTable/type'
import { addDialog } from '@/components/SpDialog/index'
import ModalForm from '../form/modal.vue'
import ModalDetails from '../details.vue'
import type { FormExpose } from 'ant-design-vue/es/form/Form'
import {
  AddNoticeAPI,
  deleteNoticeAPI,
  getNoticeList,
  revokedNoticeAPI,
  updateNoticeAPI
} from './api'
import type { ListByUserMessageType, ListNoticeParams, NoticeType } from './model'
import { tagListColor } from '@/constant/tag'
import { usePublicHook } from '@/views/admin/system/notice/utils/publicHook'
import { getDeptTreeAPI } from '@/views/admin/system/dept/utils/api'
import type { SysDeptListType } from '@/views/admin/system/dept/utils/model'
import { getDictDataListAPI } from '@/views/admin/system/dict/utils/api'
import type { SysDictionaryDataType } from '@/views/admin/system/dict/utils/model'
import { getPostListAPI } from '@/views/admin/system/post/utils/api'
import type { SysPostListType } from '@/views/admin/system/post/utils/model'
import type { SysRoleListType } from '@/views/admin/system/role/utils/model'
import { getRoleListAPI } from '@/views/admin/system/role/utils/api'
import { getUserSelectAPI } from '@/views/admin/system/user/utils/api'
import type { SysUserListSelectType } from '@/views/admin/system/user/utils/model'

export function useNotice() {
  const columns: SpColumnsType[] = [
    {
      title: 'id',
      dataIndex: 'id',
      width: 100,
      align: 'center'
    },
    {
      title: '标题',
      dataIndex: 'title',
      width: 100,
      align: 'center'
    },
    {
      title: '发布人',
      dataIndex: 'username',
      width: 100,
      align: 'center'
    },
    {
      title: '消息类型',
      dataIndex: 'messageType',
      width: 100,
      align: 'center',
      cellRenderer: (record: NoticeType) => (
        <>
          {messageTypeList.value.map((item, i) => {
            if (record.messageType == item.dictValue) {
              return <Tag color={tagListColor[i]}>{item.dictName}</Tag>
            }
          })}
        </>
      )
    },
    {
      title: '通知对象',
      dataIndex: 'notificationObject',
      width: 100,
      align: 'center',
      cellRenderer: (record: NoticeType) => (
        <>
          <Tag color={getNotificationObjectTag(record.noticeType)}>
            {getNotificationObjectTag(record.noticeType, true)}
          </Tag>
        </>
      )
    },
    {
      title: '发布时间',
      dataIndex: 'createTime',
      width: 120,
      align: 'center'
    },
    {
      title: '状态',
      dataIndex: 'status',
      cellRenderer: (record: NoticeType) => {
        if (record.status === 0) {
          return <Tag color="red">已撤销</Tag>
        } else {
          return <Tag color="green">正常</Tag>
        }
      },
      width: 100,
      align: 'center'
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: 120,
      align: 'center'
    }
  ]
  const { getNotificationObjectTag } = usePublicHook()
  const messageTypeList = ref<SysDictionaryDataType[]>([])
  // 用户列表
  const userList = ref<SysUserListSelectType[]>([])
  // 通知公告列表
  const dataList = ref<NoticeType[]>([])
  // 请求参数
  const queryParams = ref<ListNoticeParams>({
    pageNum: 1,
    pageSize: 5,
    total: 0
  })
  // 加载状态
  const loading = ref(false)
  // 选中项
  const selectedRowKeys = ref<number[]>([])
  // 弹窗框Ref
  const modalRef = ref()
  // 岗位列表数据
  const postList = ref<SysPostListType[]>([])
  // 部门树
  const treeData = ref<SysDeptListType[]>([])
  // 角色列表数据
  const roleList = ref<SysRoleListType[]>([])

  // 获取通知公告列表
  function getDataList() {
    loading.value = true
    getNoticeList(queryParams.value).then((res) => {
      dataList.value = res.data.rows
      queryParams.value.total = res.data.total
      loading.value = false
    })
  }

  // 获取用户列表
  function getUserList() {
    getUserSelectAPI().then((res) => {
      userList.value = res.data
    })
  }

  /** 获取角色列表 */
  function getRoleList() {
    getRoleListAPI({ pageNum: 1, pageSize: 99999 }).then((res) => {
      roleList.value = res.data.rows
    })
  }

  // 获取消息类型字典
  function getMessageTypeList() {
    getDictDataListAPI('system_message_type').then((res) => {
      messageTypeList.value = res.data
    })
  }

  /** 获取岗位列表 */
  function getPostList() {
    getPostListAPI({ pageNum: 1, pageSize: 99999 }).then((res) => {
      postList.value = res.data.rows
    })
  }

  // 获取部门树数据
  function getDeptTreeData() {
    getDeptTreeAPI().then((res) => {
      treeData.value = res.data
    })
  }

  // 打开弹窗
  function openModal(title: string, data?: ListByUserMessageType) {
    addDialog({
      title: `${title}通知公告`,
      fullScreen: true,
      keyboard: false,
      contentRenderer: () =>
        h(ModalForm, {
          ref: modalRef,
          userList: userList.value ?? [],
          data,
          postList: postList.value ?? [],
          treeData: treeData.value ?? [],
          roleList: roleList.value ?? []
        }),
      beforeSure: function (done) {
        // 关闭弹窗
        function chores(title: string, name: string, done: Function) {
          message.success(`您${title}了通知公告名称为${name}的这条数据`)
          done()
          getDataList()
        }

        const form = modalRef.value.getRef() as FormExpose
        form.validate().then((res) => {
          const formData = res as NoticeType
          if (formData.targetIds == undefined) {
            formData.targetIds = []
          }
          console.log(formData)
          if (title == '新增') {
            AddNoticeAPI(formData).then(() => {
              chores(title, formData.title, done)
            })
          } else {
            updateNoticeAPI(data?.id as number, formData).then(() => {
              chores(title, formData.title, done)
            })
          }
        })
      }
    })
  }

  // 查看详情
  function openDetails(data: ListByUserMessageType) {
    addDialog({
      title: `查看通知公告`,
      width: '80%',
      footer: false,
      contentRenderer: () =>
        h(ModalDetails, {
          data
        })
    })
  }

  /**
   * 撤销通知公告
   * @param id
   */
  function revokedNotice(id: number) {
    revokedNoticeAPI(id).then(() => {
      message.success(`撤销成功`)
      getDataList()
    })
  }

  // 删除
  const deleteData = ({ id }: NoticeType) => {
    deleteNoticeAPI(id as number).then(() => {
      message.success(`删除成功`)
      getDataList()
    })
  }

  // 批量删除
  function batchDeleteChange() {}

  // 选中项
  const onSelectChange = (keys: number[]) => {
    console.log('selectedRowKeys changed: ', selectedRowKeys)
    selectedRowKeys.value = keys
  }

  // 分页
  function paginationChange(paging: number, size: number) {
    queryParams.value.pageNum = paging
    queryParams.value.pageSize = size
    getDataList()
  }

  // 清空
  function clear() {
    queryParams.value = Object.assign({
      pageNum: 1,
      pageSize: 5,
      messageType: ''
    })
    getDataList()
  }

  // 搜索
  function search() {
    queryParams.value.pageNum = 1
    getDataList()
  }

  onMounted(() => {
    getDataList()
    getMessageTypeList()
    getUserList()
    getPostList()
    getDeptTreeData()
    getRoleList()
  })

  return {
    openModal,
    deleteData,
    search,
    clear,
    batchDeleteChange,
    onSelectChange,
    paginationChange,
    revokedNotice,
    openDetails,
    dataList,
    columns,
    queryParams,
    loading,
    selectedRowKeys
  }
}
